package com.qianfeng.qlm.handforireader.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.qianfeng.qlm.handforireader.R;
import com.qianfeng.qlm.handforireader.model.NewBean;
import com.qianfeng.qlm.handforireader.model.NewBeanList;
import com.qianfeng.qlm.handforireader.util.BitmapHelp;
import com.qianfeng.qlm.handforireader.util.Constant;

import java.util.ArrayList;
import java.util.List;

import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter;

public class StickyListViewBaseAdapter extends BaseAdapter implements
        StickyListHeadersAdapter, SectionIndexer {

    private final Context mContext;
    private String[] mCountries;
    private int[] mSectionIndices;
    private Character[] mSectionLetters;
    private LayoutInflater mInflater;
    private List<NewBean> data;
    private final RequestQueue requestQueue;

    private String[] strWeeks = new String[]{
            "星期一","星期二","星期三","星期四","星期五","星期六","星期日"
    };

    public StickyListViewBaseAdapter(Context context, List<NewBean> data) {
        mContext = context;
        mInflater = LayoutInflater.from(context);
        mCountries = context.getResources().getStringArray(R.array.countries);
        this.data = data;
        BitmapHelp.initUtils(context);
        requestQueue = Volley.newRequestQueue(mContext);

    }


    private Character[] getSectionLetters() {
        Character[] letters = new Character[mSectionIndices.length];
        for (int i = 0; i < mSectionIndices.length; i++) {
            letters[i] = mCountries[mSectionIndices[i]].charAt(0);
        }
        return letters;
    }

    @Override
    public int getCount() {
        int ret = 0;
        if (data != null){
            ret = data.size();
        }
        return ret;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.new_item, parent, false);
            holder.image = (ImageView) convertView.findViewById(R.id.new_item_image);
            holder.title = (TextView) convertView.findViewById(R.id.item_title);
            holder.author = (TextView) convertView.findViewById(R.id.item_author);
            holder.update = (TextView) convertView.findViewById(R.id.item_update_time);
            holder.desc = (TextView) convertView.findViewById(R.id.item_desc);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        final ImageView imgView = holder.image;

        if (data != null){
            NewBean bean = data.get(position);
            holder.title.setText(bean.getComic_name());
            holder.author.setText("作者:"+bean.getPainter_user_nickname());
            holder.desc.setText(bean.getComic_desc());
            String picUrl = bean.getComic_pic_240_320();
            String lastOrderidx = bean.getComic_last_orderidx();
            holder.update.setText("更新至"+lastOrderidx+"话");


            if (picUrl != null){
                if (!picUrl.startsWith("http://") && !picUrl.equals("https://")){
                    picUrl = Constant.URL_SUFFIX + picUrl;
                }
//                ImageRequest request = new ImageRequest(
//                        picUrl,
//                        new Response.Listener<Bitmap>() {
//                            @Override
//                            public void onResponse(Bitmap response) {
//                                if (response != null){
//                                    imgView.setImageBitmap(response);
//                                }
//                            }
//                        },
//                        0,0,
//                        Bitmap.Config.ARGB_8888,
//                        new Response.ErrorListener() {
//                            @Override
//                            public void onErrorResponse(VolleyError error) {
//
//                            }
//                        }
//                );
//
//                requestQueue.add(request);

                BitmapHelp.getUtils().display(holder.image,picUrl,new BitmapLoadCallBack<ImageView>() {
                    @Override
                    public void onLoadCompleted(ImageView imageView, String s, Bitmap bitmap, BitmapDisplayConfig bitmapDisplayConfig, BitmapLoadFrom bitmapLoadFrom) {
                        if(bitmap != null){
                            imageView.setImageBitmap(bitmap);
                        }

                    }

                    @Override
                    public void onLoadFailed(ImageView imageView, String s, Drawable drawable) {
                        imageView.setImageDrawable(drawable);
                    }
                });
            }

        }

        return convertView;
    }

    @Override
    public View getHeaderView(int position, View convertView, ViewGroup parent) {
        HeaderViewHolder holder;

        if (convertView == null) {
            holder = new HeaderViewHolder();
            convertView = mInflater.inflate(R.layout.header, parent, false);
            holder.txtWeek = (TextView) convertView.findViewById(R.id.new_header_week);
            holder.txtDate = (TextView) convertView.findViewById(R.id.new_header_date);
            convertView.setTag(holder);
        } else {
            holder = (HeaderViewHolder) convertView.getTag();
        }

        if (data != null){
            NewBean bean = data.get(position);

            String weekNumber = bean.getWeek_number();
            if (weekNumber != null){
                try {
                    int weekIndex = Integer.parseInt(weekNumber);
                    weekIndex -= 1;
                    if (weekIndex >= 0 && weekIndex < strWeeks.length){
                        holder.txtWeek.setText(strWeeks[weekIndex]);
                    }

                }catch (Exception e){

                }
            }

            holder.txtDate.setText(bean.getShow_time());
        }

        return convertView;
    }

    /**
     * Remember that these have to be static, postion=1 should always return
     * the same Id that is.
     */
    @Override
    public long getHeaderId(int position) {
        // return the first character of the country as ID because this is what
        // headers are based upon
        long ret = 0;
        if (data != null){
            NewBean bean = data.get(position);
            if (bean != null){
                String weekNumber = bean.getWeek_number();
                ret = Long.parseLong(weekNumber);
            }
        }
        return ret;
    }

    @Override
    public int getPositionForSection(int section) {
        if (mSectionIndices.length == 0) {
            return 0;
        }

        if (section >= mSectionIndices.length) {
            section = mSectionIndices.length - 1;
        } else if (section < 0) {
            section = 0;
        }
        return section;
    }

    @Override
    public int getSectionForPosition(int position) {
        for (int i = 0; i < mSectionIndices.length; i++) {
            if (position < mSectionIndices[i]) {
                return i - 1;
            }
        }
        return position;
    }

    @Override
    public Object[] getSections() {
        return mSectionLetters;
    }

    public void clear() {
        mCountries = new String[0];
        mSectionIndices = new int[0];
        mSectionLetters = new Character[0];
        notifyDataSetChanged();
    }

    public void setData(List<NewBean> data){
        if (this.data != null){
            this.data.clear();
            this.data.addAll(data);
            notifyDataSetChanged();
        }
    }

    public void restore() {
        mCountries = mContext.getResources().getStringArray(R.array.countries);
//        mSectionIndices = getSectionIndices();
        mSectionLetters = getSectionLetters();
        notifyDataSetChanged();
    }

    class HeaderViewHolder {
        TextView txtWeek;
        TextView txtDate;
    }

    class ViewHolder {
        ImageView image;
        TextView title;
        TextView author;
        TextView update;
        TextView desc;
    }

}
